var express = require('express');
var router = express.Router();
var WXBizDataCrypt = require('./WXBizDataCrypt')

router.get("/openid", async (req, res) => {
  const Ut = require("../common/utils");
  try {
    let appId = "wxb3be2da6917b6f17";
    let secret = "58783fe908865ff4ee2379c5b5e2c06b";
    let js_code  = req.url;
    js_code = js_code.split("/openid?code=");
    js_code = js_code[1];
    console.log(js_code);
    let opts = {
      url: 'https://api.weixin.qq.com/sns/jscode2session?appid='+ appId + '&secret=' + secret +'&js_code='+ js_code+'&grant_type=authorization_code'
    }
    let r1 = await Ut.promiseReq(opts);
    r1 = JSON.parse(r1);
    console.log(r1);
    res.json(r1);

  }
  catch (e) {
    console.log(e);
    res.json('');
  }
});
router.post("/cryptdata", async (req, res) => {
  let WXBizDataCrypt = require('./WXBizDataCrypt')
  const sha1 = require("sha1");
  try {
    let appId = "wxb3be2da6917b6f17";
    let secret = "58783fe908865ff4ee2379c5b5e2c06b";
    let { encryptedData, iv, js_code, rawData, signature } = req.body;
    // 获取session_key
    let opts = {
      url: `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${secret}&js_code=${js_code}&grant_type=authorization_code`
    }
    let r1 = await Ut.promiseReq(opts);
    let { session_key } = JSON.parse(r1);
    if (!session_key) return res.json('');
    // 数据签名校验
    let signature2 = sha1(rawData + session_key);
    if (signature != signature2) return res.json("数据签名校验失败");
    // 解密
    let pc = new WXBizDataCrypt(appId, session_key)
 
    let data = pc.decryptData(encryptedData, iv)
 
    console.log('解密后 data: ', data)
    res.json(data);
  }
  catch (e) {
    console.log(e);
    res.json('');
  }
})




module.exports = router;
